package com.example.myapplication.preview;


import android.app.Activity;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import com.example.myapplication.R;
import com.example.util.CameraUtil;

import java.io.File;
import java.io.IOException;

public class CameraActivity extends Activity {

    private Camera mCamera;
    private CameraPreview mPreview;
    private MediaRecorder mediaRecorder;
    private static String TAG = CameraPreview.class.getName();
    private static boolean tag = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);



        // Create our Preview view and set it as the content of our activity.

        // Add a listener to the Capture button
        Button captureButton = (Button) findViewById(R.id.button_capture);
        Bundle extras = getIntent().getExtras();

        boolean equals = extras != null && "ok".equals(extras.get("v"));
        if (equals) {

            mCamera = CameraUtil.canCamera();
            mediaRecorder = new MediaRecorder();
            mPreview = new CameraPreview(this, mCamera, mediaRecorder);
            FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
            preview.addView(mPreview);

            captureButton.setOnClickListener(v -> {
                try {
                    if (mediaRecorder == null) {
                        return;
                    }
                    Button v1 = (Button) v;
                    if (!tag) {
                        prepareVideoRecorder();
                        mediaRecorder.start();
                        v1.setText("停止");
                        tag = true;
                        return;
                    }
                    mediaRecorder.stop();
                    mediaRecorder.release();
                    mCamera.lock();
                    tag = false;
                    v1.setText("开始");
                    return;
                } catch (Exception e) {
                    Log.d(this.getClass().getName(), "", e);
                }


            });
            return;
        }
        mPreview = new CameraPreview(this, mCamera);
        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(mPreview);
        captureButton.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // get an image from the camera
                        mCamera.takePicture(null, null, new Camera.PictureCallback() {

                            @Override
                            public void onPictureTaken(byte[] data, Camera camera) {
                                System.out.println(1);
                            }
                        });

                    }
                }
        );
    }

    private void releaseMediaRecorder(){
        if (mediaRecorder != null) {
            mediaRecorder.reset();   // clear recorder configuration
            mediaRecorder.release(); // release the recorder object
            mediaRecorder = null;
        }
    }

    private void releaseCamera(){
        if (mCamera != null){
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder();       // if you are using MediaRecorder, release it first
        releaseCamera();

    }
    private boolean prepareVideoRecorder(){

//        mCamera = CameraUtil.canCamera();
        // Create an instance of Camera

        mCamera.unlock();
        mediaRecorder.setCamera(mCamera);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
//        mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
        mediaRecorder.setVideoFrameRate(30);
        mediaRecorder.setVideoEncodingBitRate(((int) ((2) * 1024 * 1024)));
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
        mediaRecorder.setOutputFile(new File(getExternalCacheDir(),"123.mp4"));
        mediaRecorder.setPreviewDisplay(mPreview.getSurfaceHolder().getSurface());

        // Step 5: Set the preview output
//        mediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());

        // Step 6: Prepare configured MediaRecorder
        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
            Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage(), e);
            Log.e(TAG, e.getMessage(), e);
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage(), e);
            releaseMediaRecorder();
            return false;
        }
        return true;
    }
    /** Create a File for saving an image or video */
    private File getOutputMediaFile(int type){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = getExternalFilesDir("Pictures");

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = "UUU";
        File mediaFile;
        if (type == 1){
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_"+ timeStamp + ".jpg");
        } else if(type == 2) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "VID_"+ timeStamp + ".mp4");
        } else {
            return null;
        }
        if (!mediaFile.exists()) {
            try {
                mediaFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return mediaFile;
    }
}